package com.hyg.lib_music.ui.fragment;

import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CompoundButton;
import android.widget.Toast;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.hyg.lib_base.Net.NetworkUtils;
import com.hyg.lib_common.Base.BaseActivity;
import com.hyg.lib_common.Base.BaseApplication;
import com.hyg.lib_common.DataModel.EventBusMessage;
import com.hyg.lib_common.DataModel.Music.FavMusic;
import com.hyg.lib_common.DataModel.Music.Music;
import com.hyg.lib_common.DataModel.YangShengInfo.ReceiveDataInt;
import com.hyg.lib_common.Net.CommonHttpUtil;
import com.hyg.lib_common.constant.Constants;
import com.hyg.lib_common.sweetalertdialog.SweetAlertDialog;
import com.hyg.lib_music.R;
import com.hyg.lib_music.adapter.MusicCountViewBinder;
import com.hyg.lib_music.adapter.MusicFavListAdapter;
import com.hyg.lib_music.adapter.MusicFavViewBinder;
import com.hyg.lib_music.databinding.FragmentFavListBinding;
import com.hyg.lib_music.modle.CategoryMusicListData;
import com.hyg.lib_music.modle.FavMusicListData;
import com.hyg.lib_music.modle.RecommedMusicData;
import com.hyg.lib_music.presenter.MusicFavListContract;
import com.hyg.lib_music.presenter.di.components.DaggerActivityComponent;
import com.hyg.lib_music.service.MusicService;
import com.hyg.lib_music.ui.activity.MusicMainActivity;
import com.hyg.lib_music.util.ApplicationComponentUtil;
import com.hyg.lib_music.util.MusicChangeEvent;
import com.hyg.lib_music.util.MusicFavManager;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import javax.inject.Inject;

import me.drakeet.multitype.Items;
import me.drakeet.multitype.MultiTypeAdapter;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

import static me.drakeet.multitype.MultiTypeAsserts.assertAllRegistered;
import static me.drakeet.multitype.MultiTypeAsserts.assertHasTheSameAdapter;

public class MusicFavListFragment extends BaseFragment {
    FragmentFavListBinding binding;
    BaseActivity activity;
    MusicFavListAdapter adapter;
    List<FavMusicListData.DataDTO> list = new ArrayList<>();
    List<Music> music_list = new ArrayList<>();
    boolean needRefrash = false;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        binding = FragmentFavListBinding.inflate(inflater, container, false);
        init();
        return binding.getRoot();
    }

    public void init() {
        EventBus.getDefault().register(this);
        activity = (BaseActivity) getActivity();

        binding.tvListEdit.setOnClickListener(new View.OnClickListener() {   //编辑
            @Override
            public void onClick(View v) {
                binding.reListPlay.setVisibility(View.GONE);
                binding.reListEdit.setVisibility(View.VISIBLE);
                binding.ivCollection.setVisibility(View.VISIBLE);
                binding.ivCollection.setChecked(false);
                for (Music music : music_list) {
                    music.isEditable = true;
                }
                adapter.notifyDataSetChanged();
            }
        });
        binding.tvExitEdit.setOnClickListener(new View.OnClickListener() {              //退出编辑
            @Override
            public void onClick(View v) {
                binding.reListEdit.setVisibility(View.GONE);
                binding.ivCollection.setVisibility(View.GONE);
//                binding.reListPlay.setVisibility(View.VISIBLE);

//
//                binding.ivCollection.setVisibility(View.GONE);
//                for (Music music : music_list) {
//                    music.isEditable = false;
//                }
//                adapter.notifyDataSetChanged();
//

                if (music_list.size() == 0) {
                    binding.rcvFavList.setVisibility(View.GONE);
                    binding.reListPlay.setVisibility(View.GONE);
                }else{
                    binding.reListPlay.setVisibility(View.VISIBLE);
                    for (Music music : music_list) {
                        music.isEditable = false;
                    }
                    adapter.notifyDataSetChanged();
                }


            }
        });

        binding.ivCollection.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {   //全选
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    for (Music music : music_list) {
                        music.isChecked = true;
                    }
                } else {
                    for (Music music : music_list) {
                        music.isChecked = false;
                    }
                }
                adapter.notifyDataSetChanged();
            }
        });

        binding.lnPlayAll.setOnClickListener(new View.OnClickListener() {        //播放全部
            @Override
            public void onClick(View v) {
                if (music_list.size() > 0 && MusicMainActivity.serviceBinder != null) {
                    MusicMainActivity.result_type = "我喜欢";
                    MusicMainActivity.serviceBinder.addPlayList(music_list, music_list.get(0));
                }
            }
        });

        binding.lnEditRemove.setOnClickListener(new View.OnClickListener() {       //编辑-----移除
            @Override
            public void onClick(View v) {
                removeMusicList();
            }
        });

        binding.lnEditComplelte.setOnClickListener(new View.OnClickListener() {    //编辑-----完成
            @Override
            public void onClick(View v) {
                binding.reListEdit.setVisibility(View.GONE);
                binding.ivCollection.setVisibility(View.GONE);
                if (music_list.size() == 0) {
                    binding.rcvFavList.setVisibility(View.GONE);
                }else{
                    binding.reListPlay.setVisibility(View.VISIBLE);
                    for (Music music : music_list) {
                        music.isEditable = false;
                    }
                    adapter.notifyDataSetChanged();
                }
            }
        });
        getFavListData(true);
        initPlayerStateChangeListener();
    }

    public void getFavListData(boolean showDialog) {
        CommonHttpUtil.getFavList(getActivity(), new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                if (showDialog) {
                    activity.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            activity.ErrorDialog("服务器错误");
                        }
                    });
                }
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String result = response.body().string();
                FavMusicListData data = JSONObject.parseObject(result, FavMusicListData.class);
                list = data.getData();
                music_list.clear();
                for (FavMusicListData.DataDTO dataDTO : list) {
                    music_list.add(new Music(dataDTO.getMusicId(), dataDTO.getMusicName(), dataDTO.getMusician(), dataDTO.getMusicDuration(),
                            0, dataDTO.getMusicUrl(), true,
                            0, 0, "",
                            false, false, false));
                }
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (data.getCode() == 200) {
                            initRecyclerview(music_list);
                        } else if (showDialog) {
                            activity.ErrorDialog(data.getMessage());
                        }
                    }
                });
            }
        });
    }


    public void initRecyclerview(List<Music> list) {
        if (list.size() == 0) {
            binding.ivFavlistNone.setVisibility(View.VISIBLE);
            binding.rcvFavList.setVisibility(View.GONE);
            binding.reListEdit.setVisibility(View.GONE);
            binding.ivCollection.setVisibility(View.GONE);
            binding.reListPlay.setVisibility(View.GONE);
        } else {
            binding.ivFavlistNone.setVisibility(View.GONE);
            binding.rcvFavList.setVisibility(View.VISIBLE);
            binding.reListPlay.setVisibility(View.VISIBLE);
            LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
            binding.rcvFavList.setLayoutManager(layoutManager);
            adapter = new MusicFavListAdapter(getActivity(), list);
            binding.rcvFavList.setAdapter(adapter);
        }
    }


    private void removeMusicList() {
        Log.i("lgb", "onClick: 移除");
        ArrayList<Integer> id_list = new ArrayList<>();
        ArrayList<Music> remove_list = new ArrayList<>();
        for (Music music : music_list) {
            if (music.isChecked) {
                id_list.add(music.id);
                remove_list.add(music);
            }
        }
        if (id_list.size() == 0) return;
        CommonHttpUtil.removeMultilFavList(getActivity(), id_list.toString(), new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                activity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        activity.ErrorDialog("服务器错误");
                    }
                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String result = response.body().string();
                ReceiveDataInt dataInt = JSONObject.parseObject(result, ReceiveDataInt.class);
                activity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (dataInt.getCode() == 200) {
                            for (Music music : remove_list) {
                                if (music_list.contains(music)) {
                                    music_list.remove(music);
                                }
                            }
                            if (music_list.size() == 0) {
                                binding.ivFavlistNone.setVisibility(View.VISIBLE);
                                binding.ivCollection.setVisibility(View.GONE);
                                binding.rcvFavList.setVisibility(View.GONE);
                            } else {
                                adapter.notifyDataSetChanged();
                            }
                        } else {
                            activity.ErrorDialog(dataInt.getMessage());
                        }
                    }
                });
            }
        });
    }


    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden && needRefrash) {
            getFavListData(true);
            needRefrash = false;
        }
    }

    @Subscribe
    public void onEvent(EventBusMessage message) {
        Log.i("lgb", "onEvent:jieya " + message.getmessage());
        //接收以及处理数据
        if (message.getmessage().equals(Constants.Add_Favorite) || message.getmessage().equals(Constants.Cancel_Favorite)) {
            needRefrash = true;
        }
    }


    public void initPlayerStateChangeListener() {
        MusicMainActivity.serviceBinder.registerOnStateChangeListener(listenr);
    }

    //实现监听器监听MusicService的变化，
    private MusicService.OnStateChangeListenr listenr = new MusicService.OnStateChangeListenr() {
        @Override
        public void onPlayProgressChange(long played, long duration) {

        }

        @Override
        public void onPlay(final Music item) {
            Log.i("lgb", "onPlay: ");
            for (Music music : music_list) {
                music.isPlaying = false;
                if (music.musicName.equals(item.musicName)) {
                    music.isPlaying = true;
                }
            }
            if (adapter != null) {
                adapter.notifyDataSetChanged();
            }
        }

        @Override
        public void onPause() {
            //变为暂停状态时。
        }
    };

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (MusicMainActivity.serviceBinder != null && listenr != null) {
            MusicMainActivity.serviceBinder.unregisterOnStateChangeListener(listenr);
            listenr = null;
        }
    }
}